package com.guofang.bak;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.connectors.DirectConnector;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class FTPUtils {

	private static final int CONN_TIMEOUT = 20 * 1000;

	static class NasFTPConnector extends DirectConnector {

		public Socket connectForDataTransferChannel(String host, int port)
				throws IOException {
			Socket socket = new Socket();
			socket.setReceiveBufferSize(512 * 1024);
			socket.setSendBufferSize(512 * 1024);
			socket.connect(new InetSocketAddress(host, port), CONN_TIMEOUT);
			return socket;
		}
	}

	public static FTPClient getClient() throws Exception {
		FTPClient client = new FTPClient();
		client.setConnector(new NasFTPConnector());
		client.connect("113.240.220.215");
		client.login("anonymous", "a");
		client.setPassive(true);
		return client;

	}

	public static boolean uploadModel(String file) throws Exception {
		FTPClient client = getClient();
		try {
			client.changeDirectory("modelib");
			client.upload(new File(file));
		} finally {
			closeClient(client);
		}

		return true;

	}

	public static boolean uploadVerify(String file) throws Exception {
		FTPClient client = getClient();
		try {
			client.changeDirectory("verify");
			client.upload(new File(file));
		} finally {
			closeClient(client);
		}
		return true;
	}

	public static FTPClient getClient(String ip, String acc, String pass)
			throws Exception {
		FTPClient client = new FTPClient();
		client.setConnector(new NasFTPConnector());
		client.connect(ip);
		client.login(acc, pass);
		client.setPassive(true);
		return client;

	}

	public static boolean test(String ip, String acc, String passwd) {
		FTPClient client = null;
		try {

			client = getClient(ip, acc, passwd);

		} catch (Exception e) {
			return false;
		}

		finally {
			closeClient(client);
		}
		return true;

	}

	public static void closeClient(FTPClient client) {
		if (client != null && client.isConnected()) {
			try {
				client.disconnect(true);
			} catch (Exception e) {
				e.printStackTrace();
				// ignore 濡傛灉娌¤兘姝ｅ父鍏抽棴锛岃澶囦細涓嶄細涓诲姩瓒呮椂鏉�帀杩炴帴锛�

			}
		}
	}

}
